<%@page import="domain.Person"%>
<%@page import="domain.Mission"%>
<%@page import="util.DateUtil"%>
<%@page import="domain.ScheduleStatus"%>
<%@page import="domain.Schedule"%>
<%@page import="java.util.List"%>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html> 
<html > 
<head>
	<jsp:include page="./header.jsp" />
	
	<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
	<%
	List<Schedule> schedules = (List<Schedule>) request.getAttribute("schedules");
	List<Person> drivers = (List<Person>) request.getAttribute("drivers");
	String message = (String) request.getAttribute("message");
	Person currentUser = (Person) request.getAttribute("currentUser");
	%>
	<title>Intelligent Route System</title>
	<!--  script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=true&amp;key=ABQIAAAAwYiir9brQH570zK6R4n_gxSViLtmlsKwCN2_V3KmGYK2miLncBSFf_4CdQkwqxAkaqbQfbaWNTqk0g" type="text/javascript"></script-->
	<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAwYiir9brQH570zK6R4n_gxRE5RfvJW9wwM6GbfZe-Hhy66TqeRTi8vBudGMTBvkwiZC5EBV7C8kvnQ" type="text/javascript"></script> 
	<!-- GOOGLE MAP -->
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
	<style type="text/css">
	  html { height: 100% }
	  body { height: 100%; margin: 0px; padding: 0px }
	  #map_canvas { height: 100% }
	</style>
	<script type="text/javascript"
	    src="http://maps.google.com/maps/api/js?sensor=true">
	</script>
	<script type="text/javascript" src="./resources/BpTspSolver.js"></script>
	<script type="text/javascript" src="./resources/tsp.js"></script>
	
	<script type="text/javascript">
	//var tsp; // The BpTspSolver object which handles the TSP computation.
	var posList;
	var posListNonCentral = new Array();
	var posListCentral = new Array();
	var posListTSP;
	var posListFinal;
	var orderMission;
	var missionFromPOS;
	var missionToPOS;
	var afterTransferList = new Array();
	var transferPOS;
	var isAfterTransfer = false;
	var beforeTransferList = new Array();
	
	function updateMission(url, id){
		document.forms["updateMission"+id].method = "post";
		document.forms["updateMission"+id].action = "./"+url;
		document.forms["updateMission"+id].submit();
	}
		function initialize() {
		    
			/*var latlng = new google.maps.LatLng(13.711428,100.594103);
		    var myOptions = {
		      zoom: 8,
		      center: latlng,
		      mapTypeId: google.maps.MapTypeId.ROADMAP
		    };
		    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		    */
		    
		    //getSchedule();
			 //loadAtStart(13.711428, 100.594103, 10);
			 //getSchedule();
			 
		  }
		//window.onload = function(){ alert("tt");
		//	$('#current_date').append(print_today_eg);
		//}
		function classifyPosList(){
			var str = "";
			for( var i=0; i<posList.pos.length; i++){
				//alert(posList.pos[i].name + " --> "+posList.pos[i].isCentral);
				if(posList.pos[i].isCentral == false){
					//alert("Non Cen");
					posListNonCentral.push(posList.pos[i]);
					
				}else {
					posListCentral.push(posList.pos[i]);
					//alert("cen");
				}
				//tsp.addWaypoint(new GLatLng(posList.pos[i].lat, posList.pos[i].lng));
				
			}
			posListTSP = posListNonCentral;
			//alert("posListTSP => "+posListTSP);
			/*for(var i=0; i < posListNonCentral.length; i++){
				str += posListNonCentral[i].name + " ... ";
			}
			alert(str);
			*/
		}
		function getSchedule() {
			
			
	
			/*var gebMap = new GMap2(document.getElementById("map"));
			 gebMap.setCenter(new GLatLng(13.711428, 100.594103), 8);
			gebMap.addControl(new GLargeMapControl());
			gebMap.addControl(new GMapTypeControl());
			*/
		 var   tsp = new BpTspSolver(new GMap2(document.getElementById("map")),document.getElementById("my_textual_div"));
		   // var request = createXMLHttpRequest();
			//request.open('get','./AJAX?todo=getPOS&scheduleId=501',false);
			//request.send(null);
			//posList = eval("(" + request.responseText + ")");
			//alert('<posList.pos.length = '+posList.pos.length);
			//for( var i=0; i<posList.pos.length; i++){
				//tsp.addWaypoint(new GLatLng(posList.pos[i].lat, posList.pos[i].lng));
			//var str="";
			//tsp.freeWayPoint();
			tsp.startOver();
			//alert("posListTSP.length => "+posListTSP.length);
			for(var i=0; i < posListTSP.length; i++){
				//str += posListTSP[i].id +",";
				//alert(posListTSP[i].name);
				if(posListTSP[i] != undefined){
					tsp.addWaypoint(new GLatLng(posListTSP[i].lat, posListTSP[i].lng));	
				} 
				
			
				
				//drawMarker(new GLatLng(posList.pos[i].lat, posList.pos[i].lng), tsp.getWaypoints().length);
			}
			//alert("posListTSP => "+str);
			tsp.setAvoidHighways(false);
			tsp.setTravelMode(G_TRAVEL_MODE_DRIVING);

			 tsp.solveRoundTrip(onSolveCallback2);
			// showMission();
		}
	

		function onSolveCallback2(myTsp) {
			  
			 // orderStr = "";
			//  for (var i = 0; i < tsp.getOrder().length; ++i) {
			//    orderStr += tsp.getOrder()[i] + " ";
			//  }
			 // document.getElementById("ordering").innerHTML = orderStr;

		}
		var animatedMision1 = "";
		var animatedMision2 = "";
			function moveMission(move,i){
				//alert(orderMission + " " +  i +" "+ down);
				var tmp;
				if(move=="down"){
					tmp =posListFinal[i+1];
					posListFinal[i+1]=posListFinal[i];
					posListFinal[i]=tmp;
					animatedMision1 = i;
					animatedMision2 = (i+1);
				}else if(move=="up"){
					tmp =posListFinal[i-1];
					posListFinal[i-1]=posListFinal[i];
					posListFinal[i]=tmp;
					animatedMision1 = i;
					animatedMision2 = (i-1);
				}
				/*var tmp;
				if(move=="down"){
					tmp =orderMission[i+1];
					orderMission[i+1]=orderMission[i];
					orderMission[i]=tmp;
				}else if(move=="up"){
					tmp =orderMission[i-1];
					orderMission[i-1]=orderMission[i];
					orderMission[i]=tmp;
				}*/
				
				showMissionTable();
			}
			function saveMission(){
				var str = "";
				for(var i = 0 ;i<posListFinal.length;i++){
					//str += posListFinal[parseInt(orderMission[i])].id +":";
					str += posListFinal[i].id +":";
					//posList.pos[parseInt(orderMission[i])].id +":";
				}
				//alert(str);
				document.getElementById("missionList").value = str;
			}
			function showMissionTable(){
				$('#missionTable2').html("");
				for(var i = 1 ;i<posListFinal.length;i++){
					//alert(posListFinal[parseInt(orderMission[i])]);
					$('#missionTable2').append("<span id='animated"+i+"'>"+posListFinal[i].name+"</span>"); 
					
					if((animatedMision1!="" && animatedMision2!="") && (i==animatedMision1 || i==animatedMision2) ){
						$('#animated'+i).hide().fadeIn(1200);
					}
					
					if(i<=1){
						$('#missionTable2').append("<img src='./resources/images/arrow-down.png' onClick='moveMission(\"down\","+i+")' style='cursor: pointer; float: right;'/>");
					}else if(i>=posListFinal.length-1){
						$('#missionTable2').append("<img src='./resources/images/arrow-up.png' onClick='moveMission(\"up\","+i+")' style='cursor: pointer; float: left;'/> ");
					}else {
						$('#missionTable2').append("<img src='./resources/images/arrow-up.png' onClick='moveMission(\"up\","+i+")' style='cursor: pointer; float: left;'/>&nbsp;"); 
						$('#missionTable2').append("<img src='./resources/images/arrow-down.png' onClick='moveMission(\"down\","+i+")' style='cursor: pointer; float: right;'/>");
					}
					
					
					$('#missionTable2').append("<br><hr>");
				}
				//missionTableStr += "</ul>";
				//alert('missionTableStr = '+missionTableStr)
				//var missionView = document.getElementById("missionTable2");
				//missionView.innerHTML = missionTableStr;
				saveMission();
			}
			function checkTransferCase(bestPath){
				orderMission = bestPath.toString().split(",");
				//alert("orderMission -> "+orderMission);
				
				var isTransfer = false;
				for(var i=1;i<orderMission.length -1 ; i++){
					var request = createXMLHttpRequest();
					request.open('get','./AJAX?todo=checkMissionTransferCase&missionId='+posList.pos[orderMission[i]].missionId,false);
					request.send(null);
					var mission = eval("(" + request.responseText + ")");
					if(mission.mArray[0].transfer == "transfer"){
					//	alert(mission.mArray[0].toPOS + " :: "+mission.mArray[0].transferFromPOS);
						if(mission.mArray[0].toPOS == mission.mArray[0].transferToPOS){
							missionFromPOS = mission.mArray[0].transferFromPOS;
							missionToPOS = mission.mArray[0].transferToPOS;
							//alert(mission.mArray[0].transferToPOS);
							for(var i =0;i<posListTSP.length;i++){
								if(posListTSP[i].id == mission.mArray[0].toPOS){
									//alert("im here ..");
									var posTmp = new Array();
									for(var j=0;j<posListTSP.length;j++){
										if(posListTSP[i] != posListTSP[j]){
											posTmp.push(posListTSP[j]);	
										}else {
											transferPOS = posListTSP[j];
										} 
											
										
									}
									posListTSP = posTmp;
									//posListTSP.slice(i, 1);
									isTransfer = true;
									
									break;
								}
							}
						}
					}
				}
				if(isTransfer == true){
					//alert("getSchedule()");
					//alert("posListTSP -> "+posListTSP);
					getSchedule();
					
				}else {
					if(isAfterTransfer == false){
						afterCheckTransfer();
						isAfterTransfer = true;
					}else {
					
						combineTransferListWithAfterTransferList();
						//posListFinal = posListTSP ; //posListNonCentral;
						//alert("posListFinal  => "+posListFinal );
						
						posListFinal = posListFinal.concat(posListCentral);
						
						
						showMissionTable();
					}
				}
					//if(posList.pos[orderMission[i]])
				//}
				//alert(orderMission);
				
				
			}
			function afterCheckTransfer(){
				var canInsert = false;
				beforeTransferList = posListTSP ;
				for(var i =0;i<posListTSP.length;i++){
					if(posListTSP[i].id == missionFromPOS || canInsert){
						canInsert = true;
						if((i+1) < posListTSP.length ){
							afterTransferList.push(posListTSP[i+1]);
						}
					}
				}
				afterTransferList.push(transferPOS);
				//alert("afterTransferList => "+afterTransferList);
				posListTSP = new Array();
				for(var i =0;i<afterTransferList.length;i++){
					if(afterTransferList!= undefined){
						posListTSP.push(afterTransferList[i]);
					}
				}
				//posListTSP = afterTransferList;
				getSchedule();
			}
			function combineTransferListWithAfterTransferList(){
				var tempList = new Array();
				var isFound = false;
				var str = "before   => ";
				//alert("beforeTransferList => "+beforeTransferList);
				for(var i =0;i<beforeTransferList.length;i++){
					
					if(beforeTransferList[i].id == missionFromPOS ){
						isFound = true;
						
					}
					tempList.push(beforeTransferList[i]);
					str += " :: "+beforeTransferList[i].name;
					if(isFound){
						break;
					}
				}
				//alert("tempList => "+tempList +"   orderMission => "+orderMission);
				
				var temp = new Array();
				str +="     after=>  ";
				for(var i=0;i<posListTSP.length-1;i++){
					temp.push(posListTSP[orderMission[i]]);
					str += " :: " + posListTSP[orderMission[i]].name;
				}
				var temp2 = new Array();
				
				
				posListFinal = tempList.concat(temp);
				//alert(str);
				//alert(posListFinal);
			}
			function showMission(bestPath){
				orderMission = bestPath.toString().split(",");
				//alert('orderMission = '+ bestPath);
				var missionTableStr = "";//"<ul data-role='listview' data-inset='true' >";
				//alert('orderMission.lenght = '+orderMission);
				//alert('orderMission.lenght = '+orderMission.length);
				showMissionTable(orderMission);
			}

	</script>
</head>
<body onload="initialize()" >
	<form id="homeSubmit">
		<input type="hidden" name="todo" value="home"/>
	</form>
	<div data-role="page" data-theme="a">

	<div data-role="header" data-backbtn="true" data-position="inline">
		<!--  a data-rel="back">Back</a-->
		<h1>Manage Schedule</h1>
		<a href="javascript:homeSubmit('Login')" data-icon="home" class="ui-btn-right" data-iconpos="notext"></a>
	</div><!-- /header -->

	<div data-role="content">
	<div id="current_date" style="text-align: right;"></div>	
		<div align="center" id="map_canvas"></div>
		
		<div id="map" style="width: 0px; height: 0px; display:none;" ></div>
		<div id="my_textual_div" style="display:none"></div>
		
		<div id="ordering2" style="display:none"></div>
		
		
		<% 
				if(schedules!=null){
			%>
			<ul data-role="listview" data-inset="true" data-theme="a">
			<%
				for(int i=0; i<schedules.size(); i++){
					Schedule schedule = schedules.get(i);
			%>
					<li>
						<a href="#missions<%= schedule.getId()%>" data-transition="slide">
							<%=schedule.getRoute()%> - <%= DateUtil.getDDMMYYYYFromDate(schedule.getDate(), 0) %>
							(<%=schedule.getStatus().equals(ScheduleStatus.completed)? schedule.getStatus(): schedule.getNoOfCompletedMissions()+"/"+schedule.getNoOfAllMissions()%>)
						</a>
					</li>
				<%} %>
			</ul>
			<%}else{ %>
				<script>
					alert("There is no any schedule!!");
				</script>
			<%} %>
			</div><!-- /content -->

	<div data-role="footer" class="ui-bar">
			<h4><%=currentUser.getFullName() %></h4>
	</div><!-- /footer -->
	</div><!-- /page -->
	
	<!-- Mission Pages -->
		<% 
			if(schedules!=null){
		%>
		<%
			for(int i=0; i<schedules.size(); i++){
				Schedule schedule = schedules.get(i);
				List<Mission> missions = schedule.getMissions();
		%>
				<div data-role="page" id="missions<%=schedule.getId()%>" data-theme="a">
			
				<div data-role="header">
					<h1><%=schedule.getRoute()%> - <%= DateUtil.getDDMMYYYYFromDate(schedule.getDate(), 0) %></h1>
				</div><!-- /header -->
			
				<div data-role="content">
				<script type="text/javascript">
					var request = createXMLHttpRequest();
					request.open('get','./AJAX?todo=getUnPrioritizePOS&scheduleId=<%=schedule.getId()%>',false);
					request.send(null);
					posList = eval("(" + request.responseText + ")");
					//alert('posList = '+posList);
					classifyPosList();
					getSchedule();
				</script>
				<div id="missionTable2" style="text-align: center;">
					
				</div>
				<form id="updateMission<%=schedule.getId() %>">
				<div data-role="fieldcontain">
				<label for="select-choice-1" class="select">Choose Driver:</label>
						<select name="select-driver" id="select-choice-1">
							<%
								for(Person p: drivers){
							%>
							<option value=<%=p.getId()%> ><%=p.getFullName() %></option>
							
							<%} %>
						</select>
				</div>	
				
							<input type="hidden" value="<%=schedule.getId() %>" name="scheduleId" id="scheduleId"/>
							<input type="hidden" value="" name="missionList" id="missionList" />
						</form>
						<br/>
							<div data-role="button" data-theme="a" onclick="updateMission('ManageSchedule', <%=schedule.getId() %>)">Update Schedule</div>
				
				</div><!-- /content -->
			
				<div data-role="footer">
					<h4><%=currentUser.getFullName() %></h4>
				</div><!-- /footer -->
				</div><!-- /page -->
			<%} %>
		<% } %>
</body>
</html>